package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;

import com.lanjiu.lib.imclient.dto.FriendDto;
import com.lanjiu.lib.imclient.dto.GroupDto;
import com.lanjiu.lib.imclient.dto.GroupMemberDto;
import com.lanjiu.lib.imclient.dto.user.UserDto;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.ModifyRemarkView;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.nic.view.util.JToast;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 修改备注名
 */
public class ModifyRemarkActivity extends AppEventActivity<ModifyRemarkView> {

    public final static int OPTION_NICK = 1;        // 修改
    public final static int OPTION_GROUP_NAME = 2;  // 修改群名称操作
    public final static int OPTION_ALIAS = 3;   // 修改备注操作
    public final static int OPTION_ALIAS_SEARCH = 4;    // 修改备注(搜索页)
    public final static int OPTION_ALIAS_GM = 5;    // 修改群成员备注

    @BindView(R.id.text_input)
    TextInputLayout textInput;

    private int mOption;
    private String targetId;
    private String targetType;
    private String targetGroup;
    private String mCurrentUserMember;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_modify_remark;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        getToolbarRightTv().setVisibility(View.VISIBLE);
        getToolbarRightTv().setText("完成");
        getToolbarRightTv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Editable input = textInput.getEditText().getText();
                if (null == obtainView()) return;
                if (mOption == OPTION_NICK) {
                    if (input == null || TextUtils.isEmpty(input)) {
                        textInput.getEditText().setError("不能为空");
                        return;
                    }
                    obtainView().doModifyRemark(input.toString());
                } else if (mOption == OPTION_ALIAS) {
                    String alias = input == null ? "" : input.toString();
                    obtainView().doModifyFriendAlias(targetId, targetType, alias);
                } else if (mOption == OPTION_GROUP_NAME) {
                    if (input == null || TextUtils.isEmpty(input)) {
                        textInput.getEditText().setError("不能为空");
                        return;
                    }
                    obtainView().doModifyGroupName(targetId, input.toString());
                } else if (mOption == OPTION_ALIAS_GM) {
                    String alias = input == null ? "" : input.toString();
                    obtainView().doModifyGroupMemberAlias(targetGroup, mCurrentUserMember, targetId, alias);
                }
            }
        });
        String title = getIntent().getStringExtra(Canstants.KEY_TITLE);
        getToolbar().setTitle(title);
        textInput.setHint(title);

        String nickname = getIntent().getStringExtra(Canstants.KEY_NICKNAME);
        if (!TextUtils.isEmpty(nickname)) textInput.getEditText().setText(nickname);
        mOption = getIntent().getIntExtra(Canstants.KEY_OPTION, 0);
        targetId = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_ID);
        targetType = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_TYPE);
        targetGroup = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_GROUP);
        mCurrentUserMember = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_MEMBER);
    }

    @Override
    protected ModifyRemarkView bindNettyMessageView() {
        return new ModifyRemarkView(new ModifyRemarkView.ModifyRemarkCallback() {
            @Override
            public void onModifyRemark(int code, String msg, UserDto data) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    UserTableBean u = UserTableBean.getCurrentUser();
                    u.setNickname(textInput.getEditText().getText().toString());
                    UserTableBean.update(u);

                    Intent intent = getIntent();
                    intent.putExtra(Canstants.KEY_REMARK, textInput.getEditText().getText().toString());
                    setResult(Canstants.KEY_REMARK_RESULT, intent);
                    finish();
                } else {
                    JToast.showShort(ModifyRemarkActivity.this, msg);
                }
            }

            @Override
            public void onModifyFriendAlias(int code, String msg, FriendDto data) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    String friendUserId;
                    String friendAlias;
                    if (data != null && !TextUtils.isEmpty(data.getFriendUserId())) {
                        friendUserId = data.getFriendUserId();
                        friendAlias = data.getFriendAlias();
                    } else {
                        friendUserId = targetId;
                        friendAlias = textInput.getEditText().getText().toString();
                    }
                    FriendTable t = FriendTable.getTableByFriendUserId(friendUserId);
                    if (t != null) {
                        t.setFriendAlias(friendAlias);
                        DbController.getInstance().getWrite().getFriendTableDao().update(t);
                    }

                    ChatContentTable ct = ChatContentTable.queryChatContentByUserId(friendUserId, Canstants.SINGLE_CHAT);
                    if (ct != null) {
                        ct.setAlias(friendAlias);
                        DbController.getInstance().getWrite().getChatContentTableDao().update(ct);
                    }

                    Intent intent = getIntent();
                    intent.putExtra(Canstants.KEY_REMARK, friendAlias);
                    setResult(Canstants.KEY_REMARK_RESULT, intent);
                    finish();
                } else {
                    JToast.showShort(ModifyRemarkActivity.this, msg);
                }
            }

            @Override
            public void onModifyGroupName(int code, String msg, GroupDto data) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    GroupTable groupTable = GroupTable.queryRowByGroupId(targetId);
                    if (null != groupTable) {
                        groupTable.setGroupName(textInput.getEditText().getText().toString());
                        DbController.getInstance().getWrite().getGroupTableDao().update(groupTable);
                    }
                    ChatContentTable ct = ChatContentTable.queryChatContentByUserId(targetId, Canstants.GROUP_CHAT);
                    if (ct != null) {
                        ct.setTargetName(textInput.getEditText().getText().toString());
                        DbController.getInstance().getWrite().getChatContentTableDao().update(ct);
                    }

                    Intent intent = getIntent();
                    intent.putExtra(Canstants.KEY_REMARK, textInput.getEditText().getText().toString());
                    setResult(Canstants.KEY_REMARK_RESULT, intent);
                    finish();
                } else {
                    JToast.showShort(ModifyRemarkActivity.this, msg);
                }
            }

            @Override
            public void onModifyGroupMemberAlias(int code, String msg, GroupMemberDto data) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<GroupMemberTable>() {
                        @Override
                        public void onAction(GroupMemberTable obj) {
                            if (obj != null) {
                                Intent intent = getIntent();
                                intent.putExtra(Canstants.KEY_REMARK, obj.getGroupMemberAlias());
                                setResult(Canstants.KEY_REMARK_RESULT, intent);
                            }
                            finish();
                        }

                        @Override
                        public GroupMemberTable onThreadAction() {
                            GroupMemberTable query = GroupMemberTable.query(targetGroup, targetId);
                            if (query != null) {
                                query.setGroupMemberAlias(textInput.getEditText().getText().toString());
                                DbController.getInstance().getWrite().getGroupMemberTableDao().update(query);
                            }
                            return query;
                        }
                    });
                } else {
                    JToast.showShort(ModifyRemarkActivity.this, msg);
                }
            }
        });
    }

    @Deprecated
    public static void jumpTo(Activity activity, String title, int requestCode) {
        Intent intent = new Intent(activity, ModifyRemarkActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_TITLE, title);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void jumpTo(Activity activity, int option, String title, String nickname, int requestCode) {
        Intent intent = new Intent(activity, ModifyRemarkActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_TITLE, title);
        intent.putExtra(Canstants.KEY_OPTION, option);
        intent.putExtra(Canstants.KEY_NICKNAME, nickname);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void jumpToModifyFriendAlias(Activity activity, String friendId, String friendUserType) {
        Intent intent = new Intent(activity, ModifyRemarkActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_TITLE, "修改备注");
        intent.putExtra(Canstants.KEY_OPTION, OPTION_ALIAS);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, friendId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_TYPE, friendUserType);
        activity.startActivityForResult(intent, Canstants.KEY_REMARK_RESULT);
    }

    public static void jumpToModifyGroupMemberAlias(Activity activity, String groupId, String memberId, String groupMemberId) {
        Intent intent = new Intent(activity, ModifyRemarkActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_TITLE, "修改备注");
        intent.putExtra(Canstants.KEY_OPTION, OPTION_ALIAS_GM);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, groupMemberId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_GROUP, groupId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_MEMBER, memberId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_TYPE, IMSUtils.userTypeAnalysis(groupMemberId));
        activity.startActivityForResult(intent, Canstants.KEY_REMARK_RESULT);
    }

    public static void jumpToModifyGroupName(Activity activity, String groupId) {
        Intent intent = new Intent(activity, ModifyRemarkActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_TITLE, "修改群名称");
        intent.putExtra(Canstants.KEY_OPTION, OPTION_GROUP_NAME);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, groupId);
        activity.startActivityForResult(intent, Canstants.KEY_REMARK_RESULT);
    }

}
